package com.firewolf.entities.n2one;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class MainDriver {
	
	private EntityManagerFactory factory = null;
	private EntityManager manager = null;
	private EntityTransaction tx = null;
	
	@Before
	public void init(){
		factory = Persistence.createEntityManagerFactory("jpa");
		manager = factory.createEntityManager();
		tx = manager.getTransaction();
		tx.begin();
	}
	
	@After
	public void destory(){
		tx.commit();
		manager.close();
		factory.close();
	}
	
	@Test
	public void generateTable(){
	}
	
	/**
	 * 保存:
	 * 建议先保存1的一端，因为如果先保存多的一端，还会生成update语句
	 */
	@Test
	public void persist(){
		Customer c = new Customer();
		c.setName("liuxing");
		c.setAge(12);
		
		Order o = new Order();
		o.setOrderName("Order-1");
		o.setCustomer(c);
		
		Order o2 = new Order();
		o2.setOrderName("Order-2");
		o2.setCustomer(c);
		
		manager.persist(c);
		manager.persist(o);
		manager.persist(o2);
	}
	
	/**
	 * 查询多的一端，默认情况下，一的一端是立即加载的，如果需要懒加载，则设置fetch为lazy
	 */
	@Test
	public void find(){
		Order c = manager.find(Order.class, 1);
		System.out.println(c);
	}
	
	/**
	 * 删除的话，如果直接删1的一端，是会报外检约束异常的
	 */
	@Test
	public void delete(){
		Customer customer = manager.find(Customer.class, 1);
		manager.remove(customer);
	}
	
	@Test
	public void update(){
		manager.find(Order.class, 1).getCustomer().setName("lixuing333");
	}
}
